//
//  BK_StorePay_Tool.m
//  bestkeep
//
//  Created by TOPTEAM on 2017/3/31.
//  Copyright © 2017年 utouu. All rights reserved.
//

#import "BK_StorePay_Tool.h"
#import "UTOTPGenerator.h"
#import "BKUserStatusInfo.h"
//#import "BK_OD_Color.h"

const int _totalDigits = 10;
@implementation BK_StorePay_Tool
+(NSString *)getPayCodeWithSeed:(NSString *)seed andUserId:(NSString *)userId andType:(NSInteger)type{
    NSData *seedData = [BK_StorePay_Tool hexToBytes:seed];
    
    UTOTPConfiguration *confiuration = [[UTOTPConfiguration alloc] initWithSecret:seedData digits:6];
    
    /*
     * 设置时间间隔
     */
    BKUserStatusInfo * userStatusInfo =[BKUserStatusInfo currentUser];
    confiuration.defaultInterval=[userStatusInfo.userValidTime integerValue];
    
    
    UTOTP *otp = [[UTTOTP alloc] initWithConfiguration:confiuration];
    
    NSString *code = [otp generateOTP];
    /*
     * 生成订单号
     */
    NSString *payCode = [BK_StorePay_Tool generatePayCode:userId code:code payType:type];
    
    return payCode;
}

+(UIImage *)Get_QRcodeImG_WithPaymentCode:(NSString *)paymentCode andSize:(CGSize)size{
  
    return [BK_StorePay_Tool generateQRCodeImage:paymentCode size:size];
    
}

+(NSData*) hexToBytes:(NSString*)str {
    NSMutableData* data = [NSMutableData data];
    int idx;
    for (idx = 0; idx+2 <= str.length; idx+=2) {
        NSRange range = NSMakeRange(idx, 2);
        NSString* hexStr = [str substringWithRange:range];
        NSScanner* scanner = [NSScanner scannerWithString:hexStr];
        unsigned int intValue;
        [scanner scanHexInt:&intValue];
        [data appendBytes:&intValue length:1];
    }
    return data;
}




+(NSString*)generatePayCode:(NSString *)userId code:(NSString *)code payType:(NSInteger)payType {
    
    
    NSInteger sum = [userId integerValue] + [code integerValue];
    NSInteger mainLength = [[NSString stringWithFormat:@"%ld", (long)sum] length];
    
    
    
    
    NSInteger prefix = mainLength + payType;
    
    NSInteger randomDigits = _totalDigits - mainLength;
    NSString *randomStr = randomDigits > 0 ? [BK_StorePay_Tool randomNumber:randomDigits] : @"";
    
    NSString *result = [NSString stringWithFormat:@"%ld%@%ld%@", (long)prefix, randomStr, (long)sum, code];
    
    return result;
}



+(NSString*)randomNumber:(NSInteger)digit {
    srandom((unsigned)time(0));
    NSMutableString *str = [NSMutableString string];
    for (int i = 0; i < digit; i++) {
        [str appendFormat:@"%ld", random() % 10];
    }
    
    return str;
}
+(UIImage*)generateQRCodeImage:(NSString *)source size:(CGSize)size
{
    NSData *data = [source dataUsingEncoding:NSUTF8StringEncoding];
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setValue:data forKey:@"inputMessage"];
    [filter setValue:@"Q" forKey:@"inputCorrectionLevel"];
    
    CIImage *cimage = filter.outputImage;
    UIImage *image = [self resizeCodeImage:cimage withSize:size];
    return image;
}

+(UIImage*)resizeCodeImage:(CIImage *)image withSize:(CGSize)size
{
    if (image) {
        CGRect extent = CGRectIntegral(image.extent);
        CGFloat scaleWidth = size.width/CGRectGetWidth(extent);
        CGFloat scaleHeight = size.height/CGRectGetHeight(extent);
        size_t width = CGRectGetWidth(extent) * scaleWidth;
        size_t height = CGRectGetHeight(extent) * scaleHeight;
        CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceGray();
        CGContextRef contentRef = CGBitmapContextCreate(nil, width, height, 8, 0, colorSpaceRef, (CGBitmapInfo)kCGImageAlphaNone);
        CIContext *context = [CIContext contextWithOptions:nil];
        CGImageRef imageRef = [context createCGImage:image fromRect:extent];
        CGContextSetInterpolationQuality(contentRef, kCGInterpolationNone);
        CGContextScaleCTM(contentRef, scaleWidth, scaleHeight);
        CGContextDrawImage(contentRef, extent, imageRef);
        CGImageRef imageRefResized = CGBitmapContextCreateImage(contentRef);
        CGContextRelease(contentRef);
        CGImageRelease(imageRef);
        return [UIImage imageWithCGImage:imageRefResized];
    }else{
        return nil;
    }
}







#pragma mark================API================
/*
接口名称：	getStorePayInfo
接口用途：	获取小店线下支付信息
method：	POST
接口地址：	pay/getStorePayInfo
输入参数：
key	参数类型	是否必须	参数解释
paymentCode	string	是	付款码
返回数据：
{
    "success": "true/false //成功/失败",
    "msg": "xxx //返回消息",
    "code": "xxx",
    "data":
    {
        "pay_way": "10:账户余额，20：支付宝，30：微信,支付方式",
        "pay_info": "支付信息",
        "pay_status": "支付状态 0：未支付，1:支付成功，2：支付失败",
    }
}
*/
+(void)BK_StorePayInfo:(BK_PS_Callback)CallBack withPaymentCode:(NSString *)paymentCode{
    NSString *const BKStorePayInfo_URL      = @"pay/getStorePayInfo";
    kOrderLoading;
    
    NSDictionary *paramDic =  @{@"paymentCode" : paymentCode};

     
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:kOrderURL(BKStorePayInfo_URL) parameters:paramDic success:^(id  _Nullable responseObject){
        
        BOOL success = [responseObject[@"success"] boolValue];
        if (!success) {
            kOrderDismiss;
            kOrderPromptMsg(responseObject[@"msg"]);
            //            return;
            CallBack(NO, nil,nil);
        }else{
            kOrderDismiss;
            CallBack(YES, responseObject,nil);
        }
        
        
    }failure:^(id  _Nullable responseObject, NSError * _Nullable error){
        kOrderDismiss;
        NSString *errorMsg;
        if (error.code == -1001) {
            errorMsg = @"请求超时";
        }else if(error.code == 502){
            errorMsg = @"服务器开小差了，请稍后再试！";
        }else{
            errorMsg = @"请求失败";
        }
        kOrderPromptMsg(errorMsg);
        CallBack(NO, nil,error);
    }];
}



@end








































